import pymysql
from dbutils.pooled_db import PooledDB, SharedDBConnection

import const
from dao import face_res_dao
import datetime as dt

COUNT = 'count'
def get_pool():
    selection = 'mysql'
    user = const.CFG.get(selection, 'user')
    pwd = const.CFG.get(selection, 'pwd')
    host = const.CFG.get(selection, 'host')
    port = const.CFG.get(selection, 'port')
    db = const.CFG.get(selection, 'db')
    return PooledDB(
        creator=pymysql,
        maxconnections=1000,
        mincached=10,
        maxshared=0,
        blocking=True,
        maxusage=None,
        host=host,
        port=int(port),
        user=user,
        password=pwd,
        database=db,
        charset='utf8'
    )

def get_conn_and_cursor():
    conn = get_pool().connection()
    cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
    return conn, cursor

def close(conn, cursor):
    cursor.close()
    conn.close()

def find_one(sql, args):
    conn, cursor = get_conn_and_cursor()
    cursor.execute(sql, args)
    res = cursor.fetchone()
    close(conn, cursor)
    return res

def find_count(sql, args):
    conn, cursor = get_conn_and_cursor()
    cursor.execute(sql, args)
    res = cursor.fetchone()
    close(conn, cursor)
    return res

def insert(sql, args):
    return inser_or_update(sql, args)

def update(sql, args):
    return inser_or_update(sql, args)

def inser_or_update(sql, args):
    conn, cursor = get_conn_and_cursor()
    row = cursor.execute(sql, args)
    conn.commit()
    close(conn, cursor)
    return row


if __name__ == '__main__':
    face_res_dao.insert(('ssssss', 'ssssssssss', 0, dt.datetime.now(), None, None))
    print('success')